﻿using System.Text;
using System.IO;
namespace WyUnity.Utility
{
	public static class FileHelper
	{
		/// <summary>
		/// 直接写入文本文件，默认编码为UTF8
		/// </summary>
		public static void WriteTextFile(string path, string text, Encoding encode = null)
		{
			if (encode == null) encode = Encoding.UTF8;
			using (var fs = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Read))
			{
				using (var sw = new StreamWriter(fs, encode))
				{
					sw.Write(text);
					sw.Flush();
				}
			}
		}
		/// <summary>
		/// 读取文本文件，默认编码为UTF8
		/// </summary>
		public static string ReadTextFile(string path, Encoding encode = null)
		{
			if (encode == null) encode = Encoding.UTF8;
			using (var sw = new StreamReader(path, encode))
			{
				return sw.ReadToEnd();
			}
		}


		/// <summary>
		/// 获取应用程序目录
		/// </summary>
		public static string GetBaseDir()
		{
			return System.AppDomain.CurrentDomain.BaseDirectory;
		}
		public static string GetFileStorageDir()
		{
			var filehome = System.Configuration.ConfigurationManager.AppSettings["File_Home"];
			if (string.IsNullOrEmpty(filehome))
				return GetBaseDir() + "\\Files";
			else
				return filehome;
		}
		/// <summary>
		/// 获取应用程序目录下的文件路径
		/// </summary>
		public static string GetFilePath(string fileName)
		{
			if (Path.IsPathRooted(fileName)) return fileName;

			return Path.Combine(GetBaseDir(), fileName);
		}
		public static byte[] ReadAllBytes(string path)
		{
			using (var fs = File.OpenRead(path))
			{
				var b = new byte[fs.Length];
				fs.Read(b, 0, b.Length);
				return b;
			}
		}
	}
}